<template>
  <div class="visitor-profile min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 返回按钮 -->
    <div class="container mx-auto px-4 py-4">
      <el-button @click="router.back()" class="back-btn" type="primary" plain>
        <el-icon class="mr-1"><Back /></el-icon>
        返回上一页
      </el-button>
    </div>

    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div
        class="header-bg"
        :style="{
          backgroundImage: `url(${userInfo.coverImage || '/images/default-cover.jpg'})`,
        }"
      ></div>
      <div class="container mx-auto px-4 py-8">
        <div class="header-content">
          <div class="user-profile">
            <div class="flex items-center gap-8 relative w-full">
              <div class="avatar-section">
                <el-avatar
                  :size="120"
                  :src="userInfo.avatar"
                  class="user-avatar ring-4 ring-white dark:ring-gray-800"
                />
              </div>
              <div class="user-info flex-1">
                <div class="flex items-center mb-4">
                  <h1 class="text-2xl font-bold text-white">
                    {{ userInfo.nickname }}
                  </h1>
                </div>
                <p class="text-gray-200 mb-4">
                  {{ userInfo.bio || "这个人很懒，什么都没写~" }}
                </p>
                <div class="user-stats flex gap-6">
                  <div
                    class="stat-item text-center cursor-pointer"
                    @click="showPostsDialog = true"
                  >
                    <div class="text-xl font-bold text-white">
                      {{ stats.postsCount }}
                    </div>
                    <div class="text-sm text-gray-200">动态</div>
                  </div>
                  <div
                    class="stat-item text-center cursor-pointer"
                    @click="showFollowingDialog = true"
                  >
                    <div class="text-xl font-bold text-white">
                      {{ stats.followingCount }}
                    </div>
                    <div class="text-sm text-gray-200">关注</div>
                  </div>
                  <div
                    class="stat-item text-center cursor-pointer"
                    @click="showFollowersDialog = true"
                  >
                    <div class="text-xl font-bold text-white">
                      {{ stats.followersCount }}
                    </div>
                    <div class="text-sm text-gray-200">粉丝</div>
                  </div>
                </div>
              </div>
              <!-- 关注按钮 -->
              <div
                class="action-buttons absolute right-0 top-1/2 -translate-y-1/2"
              >
                <el-button
                  type="primary"
                  class="follow-btn"
                  size="large"
                  @click="handleFollow"
                >
                  {{ userInfo.isFollowing ? "已关注" : "+ 关注" }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧内容区 -->
        <div class="lg:col-span-2">
          <!-- 分类导航栏 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
            <el-tabs v-model="activeTab" class="custom-tabs">
              <!-- 攻略 -->
              <el-tab-pane label="发布的攻略" name="guides">
                <div class="tab-content-wrapper">
                  <div class="space-y-4">
                    <div
                      v-for="guide in currentGuides"
                      :key="guide.id"
                      class="guide-item hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg transition-colors duration-300 p-4 cursor-pointer"
                      @click="$router.push(`/guides/${guide.id}`)"
                    >
                      <div class="flex gap-4">
                        <el-image
                          :src="guide.coverImage"
                          class="w-32 h-24 rounded-lg object-cover flex-shrink-0"
                        />
                        <div class="flex-1">
                          <h3 class="text-lg font-medium mb-2">
                            {{ guide.title }}
                          </h3>
                          <p
                            class="text-gray-600 dark:text-gray-400 text-sm mb-2 line-clamp-2"
                          >
                            {{ guide.summary }}
                          </p>
                          <div class="flex items-center text-sm text-gray-500">
                            <span>{{ formatTime(guide.createTime) }}</span>
                            <span class="mx-2">·</span>
                            <span>浏览 {{ guide.viewCount }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 分页器 -->
                  <div
                    class="flex justify-center mt-6"
                    v-if="totalGuides > pageSize"
                  >
                    <el-pagination
                      v-model:current-page="currentPage"
                      v-model:page-size="pageSize"
                      :total="totalGuides"
                      :page-sizes="[5, 10, 20]"
                      layout="total, sizes, prev, pager, next"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                    />
                  </div>
                </div>
              </el-tab-pane>

              <!-- 文章 -->
              <el-tab-pane label="发表的文章" name="articles">
                <div class="tab-content-wrapper">
                  <div class="space-y-4">
                    <div
                      v-for="article in currentArticles"
                      :key="article.id"
                      class="article-item hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg transition-colors duration-300 p-4 cursor-pointer"
                      @click="$router.push(`/community/article/${article.id}`)"
                    >
                      <h3 class="text-lg font-medium mb-2">
                        {{ article.title }}
                      </h3>
                      <p
                        class="text-gray-600 dark:text-gray-400 mb-3 line-clamp-2"
                      >
                        {{ article.summary }}
                      </p>
                      <div class="flex items-center text-sm text-gray-500">
                        <span>{{ formatTime(article.createTime) }}</span>
                        <span class="mx-2">·</span>
                        <span>阅读 {{ article.viewCount }}</span>
                      </div>
                    </div>
                  </div>
                  <!-- 分页器 -->
                  <div
                    class="flex justify-center mt-6"
                    v-if="totalArticles > pageSize"
                  >
                    <el-pagination
                      v-model:current-page="currentPage"
                      v-model:page-size="pageSize"
                      :total="totalArticles"
                      :page-sizes="[5, 10, 20]"
                      layout="total, sizes, prev, pager, next"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                    />
                  </div>
                </div>
              </el-tab-pane>

              <!-- 话题 -->
              <el-tab-pane label="参与的话题" name="topics">
                <div class="tab-content-wrapper">
                  <div class="space-y-4">
                    <div
                      v-for="topic in currentTopics"
                      :key="topic.id"
                      class="topic-item hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg transition-colors duration-300 p-4 cursor-pointer"
                      @click="$router.push(`/community/topic/${topic.id}`)"
                    >
                      <div class="flex items-center justify-between">
                        <div>
                          <h3 class="text-lg font-medium mb-1">
                            #{{ topic.name }}
                          </h3>
                          <p class="text-gray-600 dark:text-gray-400 text-sm">
                            {{ topic.description }}
                          </p>
                        </div>
                        <div class="text-sm text-gray-500">
                          参与 {{ topic.participateCount }} 次
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 分页器 -->
                  <div
                    class="flex justify-center mt-6"
                    v-if="totalTopics > pageSize"
                  >
                    <el-pagination
                      v-model:current-page="currentPage"
                      v-model:page-size="pageSize"
                      :total="totalTopics"
                      :page-sizes="[5, 10, 20]"
                      layout="total, sizes, prev, pager, next"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                    />
                  </div>
                </div>
              </el-tab-pane>

              <!-- 摄影作品 -->
              <el-tab-pane label="发布的摄影作品" name="works">
                <div class="tab-content-wrapper">
                  <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
                    <div
                      v-for="work in currentWorks"
                      :key="work.id"
                      class="work-item group relative cursor-pointer overflow-hidden rounded-lg"
                      @click="$router.push(`/photography/works/${work.id}`)"
                    >
                      <el-image
                        :src="work.imageUrl"
                        class="w-full aspect-square object-cover transition-transform duration-300 group-hover:scale-110"
                        :preview-src-list="[work.imageUrl]"
                      />
                      <div
                        class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"
                      >
                        <div class="absolute bottom-0 left-0 right-0 p-4">
                          <div class="text-white text-sm line-clamp-2">
                            {{ work.title }}
                          </div>
                          <div
                            class="flex items-center mt-2 text-xs text-gray-200"
                          >
                            <span class="flex items-center">
                              <el-icon class="mr-1"><View /></el-icon>
                              {{ work.viewCount }}
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 分页器 -->
                  <div
                    class="flex justify-center mt-6"
                    v-if="totalWorks > pageSize"
                  >
                    <el-pagination
                      v-model:current-page="currentPage"
                      v-model:page-size="pageSize"
                      :total="totalWorks"
                      :page-sizes="[6, 12, 24]"
                      layout="total, sizes, prev, pager, next"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                    />
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <!-- 右侧信息栏 -->
        <div class="sidebar space-y-6">
          <!-- 个人简介 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              个人简介
            </h3>
            <div class="space-y-4 text-gray-600 dark:text-gray-400">
              <div class="flex items-center gap-2">
                <el-icon><Location /></el-icon>
                <span>{{ userInfo.location || "暂无" }}</span>
              </div>
              <div class="flex items-center gap-2">
                <el-icon><Timer /></el-icon>
                <span>注册于 {{ formatDate(userInfo.createTime) }}</span>
              </div>
              <div class="flex items-center gap-2">
                <el-icon><Message /></el-icon>
                <span>{{ userInfo.contactInfo || "暂无联系方式" }}</span>
              </div>
              <div
                class="mt-4 pt-4 border-t border-gray-100 dark:border-gray-700"
              >
                <div class="text-sm">个人标签</div>
                <div class="flex flex-wrap gap-2 mt-2">
                  <el-tag
                    v-for="tag in userInfo.tags"
                    :key="tag"
                    size="small"
                    effect="plain"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>

          <!-- 最近访客 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                最近访客
              </h3>
              <el-button type="primary" link @click="showVisitorsDialog = true">
                查看全部
                <el-icon class="ml-1"><ArrowRight /></el-icon>
              </el-button>
            </div>
            <div class="grid grid-cols-4 gap-4">
              <div
                v-for="visitor in recentVisitors"
                :key="visitor.id"
                class="visitor-item text-center cursor-pointer group"
                @click="$router.push(`/user/profile/${visitor.id}`)"
              >
                <el-avatar
                  :size="50"
                  :src="visitor.avatar"
                  class="mb-2 ring-2 ring-transparent group-hover:ring-primary-500 transition-all duration-300"
                />
                <div
                  class="text-sm text-gray-600 dark:text-gray-400 truncate group-hover:text-primary-500 transition-colors duration-300"
                >
                  {{ visitor.nickname }}
                </div>
              </div>
            </div>
          </div>

          <!-- 相似用户推荐 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              相似用户推荐
            </h3>
            <div class="space-y-4">
              <div
                v-for="user in similarUsers"
                :key="user.id"
                class="flex items-center justify-between p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors duration-300 cursor-pointer"
                @click="$router.push(`/user/profile/${user.id}`)"
              >
                <div class="flex items-center gap-3">
                  <el-avatar :size="40" :src="user.avatar" />
                  <div>
                    <div class="font-medium text-gray-900 dark:text-white">
                      {{ user.nickname }}
                    </div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      {{ user.bio }}
                    </div>
                  </div>
                </div>
                <el-button
                  size="small"
                  :type="user.isFollowing ? 'default' : 'primary'"
                  @click.stop="handleFollowUser(user)"
                >
                  {{ user.isFollowing ? "已关注" : "关注" }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 动态弹窗 -->
    <el-dialog
      v-model="showPostsDialog"
      title="全部动态"
      width="800px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="posts-list space-y-6">
        <!-- 动态列表内容 -->
      </div>
    </el-dialog>

    <!-- 关注弹窗 -->
    <el-dialog
      v-model="showFollowingDialog"
      :title="`关注 (${stats.followingCount})`"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="following-list space-y-4">
        <!-- 关注列表内容 -->
      </div>
    </el-dialog>

    <!-- 粉丝弹窗 -->
    <el-dialog
      v-model="showFollowersDialog"
      :title="`粉丝 (${stats.followersCount})`"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="followers-list space-y-4">
        <!-- 粉丝列表内容 -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  ChatDotRound,
  Star,
  Location,
  Timer,
  ArrowRight,
  Share,
  Back,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const route = useRoute();
const router = useRouter();

// 用户信息
const userInfo = ref({
  id: route.params.id,
  nickname: "摄影师小王",
  avatar: "/images/avatars/photographer1.jpg",
  coverImage: "/images/cover/default.jpg",
  bio: "记录生活中的美好瞬间",
  location: "贵港市",
  createTime: "2024-01-01",
  isFollowing: false,
});

// 当前激活的标签页
const activeTab = ref("works");

// 统计数据
const stats = ref({
  postsCount: 25,
  followingCount: 128,
  followersCount: 256,
});

// 用户作品
const userWorks = ref([
  {
    id: 1,
    imageUrl: "/images/works/1.jpg",
    title: "贵港古镇的黄昏",
    viewCount: 234,
  },
  {
    id: 2,
    imageUrl: "/images/works/2.jpg",
    title: "江边晨曦",
    viewCount: 189,
  },
]);

// 用户文章
const userArticles = ref([
  {
    id: 1,
    title: "贵港古镇游记：一段难忘的文化之旅",
    summary: "漫步在贵港古镇的街巷中，感受历史的气息...",
    createTime: "2024-03-19 15:30:00",
    viewCount: 156,
  },
  {
    id: 2,
    title: "探访贵港美食：舌尖上的本土风味",
    summary: "贵港的美食文化源远流长，每一道菜品都蕴含着...",
    createTime: "2024-03-18 14:20:00",
    viewCount: 203,
  },
]);

// 用户参与的话题
const userTopics = ref([
  {
    id: 1,
    name: "贵港摄影",
    description: "分享贵港的自然人文风光",
    participateCount: 15,
  },
  {
    id: 2,
    name: "美食探店",
    description: "发现贵港地道美食",
    participateCount: 8,
  },
]);

// 用户发布的攻略
const userGuides = ref([
  {
    id: 1,
    title: "贵港两日游完全攻略",
    summary: "带你玩转贵港的人文景点和特色美食...",
    coverImage: "/images/guides/guide1.jpg",
    createTime: "2024-03-17 10:00:00",
    viewCount: 342,
  },
  {
    id: 2,
    title: "贵港古镇深度游攻略",
    summary: "探索古镇的历史文化底蕴，感受岁月的痕迹...",
    coverImage: "/images/guides/guide2.jpg",
    createTime: "2024-03-15 16:30:00",
    viewCount: 267,
  },
]);

// 用户动态
const userPosts = ref([
  {
    id: 1,
    content: "今天在贵港古镇拍摄，遇到了很多有趣的场景...",
    images: [
      "/images/posts/1.jpg",
      "/images/posts/2.jpg",
      "/images/posts/3.jpg",
    ],
    createTime: "2024-03-19 15:30:00",
    topic: "贵港摄影",
    commentCount: 12,
    likeCount: 34,
    shareCount: 5,
  },
  // 更多动态...
]);

// 最近访客
const recentVisitors = ref([
  {
    id: 1,
    nickname: "访客1",
    avatar: "/images/avatars/user1.jpg",
  },
  {
    id: 2,
    nickname: "访客2",
    avatar: "/images/avatars/user2.jpg",
  },
]);

// 相似用户
const similarUsers = ref([
  {
    id: 1,
    nickname: "摄影师小王",
    avatar: "/images/avatars/user1.jpg",
    bio: "专注人文摄影",
    isFollowing: false,
  },
  {
    id: 2,
    nickname: "旅行达人",
    avatar: "/images/avatars/user2.jpg",
    bio: "记录生活点滴",
    isFollowing: true,
  },
  // 更多用户...
]);

// 对话框显示状态
const showPostsDialog = ref(false);
const showFollowingDialog = ref(false);
const showFollowersDialog = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 计算总数
const totalGuides = computed(() => userGuides.value.length);
const totalArticles = computed(() => userArticles.value.length);
const totalTopics = computed(() => userTopics.value.length);
const totalWorks = computed(() => userWorks.value.length);

// 当前页数据
const currentGuides = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return userGuides.value.slice(start, end);
});

const currentArticles = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return userArticles.value.slice(start, end);
});

const currentTopics = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return userTopics.value.slice(start, end);
});

const currentWorks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return userWorks.value.slice(start, end);
});

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 监听标签页切换，重置分页
watch(activeTab, () => {
  currentPage.value = 1;
  pageSize.value = activeTab.value === "works" ? 12 : 10;
});

// 处理关注/取消关注
const handleFollow = async () => {
  try {
    userInfo.value.isFollowing = !userInfo.value.isFollowing;
    ElMessage.success(userInfo.value.isFollowing ? "关注成功" : "已取消关注");
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理关注用户
const handleFollowUser = async (user) => {
  try {
    user.isFollowing = !user.isFollowing;
    ElMessage.success(user.isFollowing ? "关注成功" : "已取消关注");
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD");
};

// 获取用户信息
const getUserInfo = async () => {
  try {
    // TODO: 调用获取用户信息API
    // const { data } = await api.getUserProfile(route.params.id)
    // userInfo.value = data
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

onMounted(() => {
  getUserInfo();
});
</script>

<style lang="scss" scoped>
.visitor-profile {
  .page-header {
    @apply relative overflow-hidden;

    .header-bg {
      @apply absolute inset-0 bg-center bg-cover bg-no-repeat;
      &::after {
        content: "";
        @apply absolute inset-0 bg-black/50;
      }
    }

    .header-content {
      @apply relative z-10;
    }

    .user-profile {
      @apply w-full;
    }

    .user-avatar {
      @apply ring-offset-2 ring-offset-white dark:ring-offset-gray-800;
    }

    .follow-btn {
      @apply min-w-[120px] text-base;
    }
  }

  .work-item {
    @apply transition-transform duration-300 hover:scale-105;
  }

  .post-item {
    @apply border-b border-gray-100 dark:border-gray-700 last:border-0 pb-6 last:pb-0;
  }

  .visitor-item {
    @apply transition-opacity duration-300 hover:opacity-80;
  }

  .custom-tabs {
    :deep(.el-tabs__header) {
      @apply mb-0 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800;
      position: sticky;
      top: 0;
      z-index: 10;
    }

    :deep(.el-tabs__nav-wrap) {
      @apply px-4;
    }

    :deep(.el-tabs__item) {
      @apply text-base font-medium px-6 py-4 transition-colors duration-300;

      &.is-active {
        @apply text-primary-600 font-semibold;
      }

      &:hover {
        @apply text-primary-500;
      }
    }

    :deep(.el-tabs__content) {
      @apply p-6;
    }
  }

  .tab-content-wrapper {
    min-height: 600px;
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    @apply space-y-4;

    &::-webkit-scrollbar {
      @apply w-2;
    }

    &::-webkit-scrollbar-track {
      @apply bg-gray-100 dark:bg-gray-700 rounded-full;
    }

    &::-webkit-scrollbar-thumb {
      @apply bg-gray-300 dark:bg-gray-600 rounded-full hover:bg-gray-400 dark:hover:bg-gray-500;
    }
  }

  .lg\:col-span-2 {
    @apply flex flex-col;
  }

  .sidebar {
    @apply sticky top-6;
  }
}

.container {
  @apply max-w-7xl mx-auto;
}
</style>
